#!/usr/local/bin/ruby -w
#database.rb

# This program takes connects to the machine idb1 and open the file 
# created by the packet, filtered.txt It parses the various fields in 
# the file like timestamp, source address, destination address etc
# and stores them into the database. Then closes the database.
#
# Author::    Tripti Singh (mailto:tripti@eden.rutgers.edu)
# Project : Packet Monitoring System for Orbit
# License::   Distributes under the same terms as Ruby
#
# This class creates the database table packet and stores the relevant # packet details in the database
       

class Database

require "mysql"

dbname = "tripti"

# Connect to the database
m = Mysql.new("idb1", "orbit", "orbit")
#r = m.query("CREATE DATABASE #{dbname}")

# Select the database to be used
m.select_db(dbname)

# If the table already exists drop the table
m.query("DROP TABLE IF EXISTS packet")

# Create a table named packet with following columns
# * Timestamp
# * Link layer Source Address
# * Link Layer Destination Address
# * Source IP Address
# * Destination IP Address
#
m.query("CREATE TABLE packet

         (
	  channel varchar(12),
          timestamp varchar(32),
          src_addr_link varchar(32),
          dst_addr_link varchar(32),
          src_addr varchar(32),
          dst_addr varchar(32)
         )"
        )
num = []

# Open the file which contain dumped packets and get the source
# address, destination address, timestamp etc
file = File.new("filtered.txt", "r")
while(line = file.gets)
line.strip!
num =  line.split(" ")

# Insert the parameters in the database
m.query("INSERT INTO packet VALUES('#{num[0]}', '#{num[1]}', '#{num[2]}', '#{num[3]}', '#{num[4]}', '#{num[5]}')")
end

# Close the connection to database
m.close

end  # end of class
